// Copyright 2019 orivil.com. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at https://mit-license.org.

package actions

import (
	"gitee.com/orivil/morgine/bundles/admin/image"
	"gitee.com/orivil/morgine/xx"
	"gitee.com/tugoer/psy-testing/code/container"
	"gitee.com/tugoer/psy-testing/code/models"
)

func GetAdvertisements(c *xx.Condition) {
	doc := xx.Doc{
		Name: "获得广告数据",
		Params: xx.Params{{
			In:     xx.Query,
			Schema: &getAdvertisementsParam{},
		}},
		Responses: xx.Responses{{
			Body: xx.MAP{"advertisements": []*models.Advertisement{{}}},
		}},
	}
	c.Doc(doc).GET().HandleFunc("/advertisements", func(ctx *xx.Context) {
		p := &getAdvertisementsParam{}
		if ctx.Unmarshal(p) {
			advertisements, err := container.Advertisements.Get(p.Page, p.Limit)
			if err != nil {
				ctx.Error(err)
			} else {
				err = InitAdvertImageUrl(advertisements)
				if err != nil {
					ctx.Error(err)
				} else {
					ctx.SendJson(xx.MAP{"advertisements": advertisements}, false)
				}
			}
		}
	})
}

func InitAdvertImageUrl(ads []*models.Advertisement) error {
	var err error
	for _, ad := range ads {
		ad.ImgUrl, err = image.Storage.GetServeUrl(ad.Img)
		if err != nil {
			return err
		}
	}
	return nil
}

func SaveAdvertisements(c *xx.Condition) {
	doc := xx.Doc{
		Name: "保存广告数据",
		Params: xx.Params{{
			In:     xx.Form,
			Schema: &saveAdvertisementsParam{},
		}},
	}
	c.Doc(doc).PUT().HandleFunc("/advertisements", func(ctx *xx.Context) {
		p := &saveAdvertisementsParam{}
		if ctx.Unmarshal(p) {
			err := container.Advertisements.Save(p.JsonBody)
			if err != nil {
				ctx.MsgWarning(err.Error())
			} else {
				ctx.MsgSuccess("已保存")
			}
		}
	})
}

type getAdvertisementsParam struct {
	Page  int `param:"page" required:""`
	Limit int `param:"limit" required:""`
}

type saveAdvertisementsParam struct {
	JsonBody string `required:"" desc:"序列化后的 JSON 字符串"`
}
